<template>
  <vDialog v-model="popShow" title="选择日期" :cancelShow="false" @onCancel="qxCancel" @onConfirm="qrCancel">
    <div class="buttons-tab dateType" v-if="showType">
      <a href="javascript:;" class="button" @click="dateType(0)"><span>近7天</span></a>
      <a href="javascript:;" class="button" @click="dateType(1)"><span>本月</span></a>
      <a href="javascript:;" class="button" @click="dateType(2)"><span>本季</span></a>
      <a href="javascript:;" class="button" @click="dateType(3)"><span>本年</span></a>
    </div>
    <p class="dateTimeMonth" v-if="showType">自选年月</p>
    <div class="m-picker-item-box" v-if="type=='Y-m'">
      <pickerItem ref="itemYear" :val.sync="year" :selType="'year'" :change="change" :d="dataList[0]"></pickerItem>
      <pickerItem ref="itemMonth" :val.sync="month" :selType="'month'" :change="change" :d="dataList[1]"></pickerItem>
      <!--<pickerItem :val.sync="day" :selType="'day'" :change="change"  :d="dataList[2]"></pickerItem>-->
    </div>
    <div class="m-picker-item-box" v-if="type=='Y-m-d'">
      <pickerItem ref="itemYear" :val.sync="year" :selType="'year'" :change="change" :d="dataList[0]"></pickerItem>
      <pickerItem ref="itemMonth" :val.sync="month" :selType="'month'" :change="change" :d="dataList[1]"></pickerItem>
      <pickerItem ref="itemDay" :val.sync="day" :selType="'day'" :change="change"  :d="dataList[2]"></pickerItem>
    </div>
  </vDialog>
</template>
<!--
selected 当天的日期字符串，例如:'2019-09-16'
startDate:''//开始时间 例如:'2019-09-16'
endDate:'', //截至时间 例如:'2019-09-16'
onConfirmDate 确认回调
-->
<script>
 import vDialog from '@/components/vDialog.vue' /* 弹框样式 */
 import pickerItem from './pickerItem.vue';
 var putil ={
   getDate(date){
     const arr = date.toString().split('-');
     arr[1] = arr[1].length ===1 && arr[1] < 10 ? '0'+arr[1]:arr[1];
     arr[2] = arr[2].length ===1 && arr[2] < 10 ? '0'+arr[2]:arr[2];
     return `${arr[0]}-${arr[1]}-${arr[2]}`
   }
 }
export default {
 components:{vDialog,pickerItem},
  data () {
    return {
      popShow:false,
      type:'Y-m',// 日期格式Y-m-d
      dataList:[],
      year:1,
      month:1,
      day:1,
      startTime:'',  //开始时间
      endTime:'',  //截至时间
      tempSelectedyear:"", //临时值
      tempSelectedmonth:"", //临时值
      tempSelectedday:"", //临时值
    }
  },
  props: {
      show:{ type:[Boolean] , default: false },
      showType:{ type:[Boolean] , default: false },//是否显示其他搜索
      startDate:{ type:[String] , default: "" },//是开始时间
      endDate:{ type:[String] , default: "" },//截至时间
      selected:{ type:[String] , default: "" },//初始化时间
  },
  computed:{
    isR(){
      return this.year%4==0?true:false;
    },
    startTimeArr(){
      if(this.startTime){
           return  this.startTime.split('-')
        }else{
            return []
        }
    },
    endTimeArr(){
        if(this.endTime){
           return  this.endTime.split('-')
        }else{
            return []
        }
    }
  },
  watch: {
      show(val, oldVal){
          this.popShow=val;
          if(this.popShow){
              document.getElementById('winbody').style.overflow = "hidden"
          }

      }
  },
  created(){
    this.popShow=this.show;
    if(this.popShow){
        document.getElementById('winbody').style.overflow = "hidden"
    }

    let date =  new Date()
    this.year=date.getFullYear();
    this.month=date.getMonth()+1,
    this.day=date.getDate();

    let years = [date.getFullYear()-50,date.getFullYear()+10];

    if(this.type=="Y-m"){
      var settings={"startTime": this.startDate ? this.startDate+"-01" : "","endTime": this.endDate ? this.endDate+"-01" : this.year+"-"+this.month+"-"+this.day};
    }else if(this.type=="Y-m-d"){
      var settings={"startTime": this.startDate,"endTime": this.endDate ? this.endDate : this.year+"-"+this.month+"-"+this.day};
    }

    // 有设置结束时间
    if(settings.endTime){
      let endY = (new Date(putil.getDate(settings.endTime))).getFullYear();
      years[1] = endY;
    }
    // 有设置开始时间
    if(settings.startTime){
      let startY = (new Date(putil.getDate(settings.startTime))).getFullYear();
      years[0] = startY;
    }
    // 两个都设置了
    if(settings.startTime && settings.endTime){
      if((new Date(putil.getDate(settings.startTime))).getTime()>=(new Date(putil.getDate(settings.endTime))).getTime()){
        years[0] = 1950;
        settings.startTime = '1950-01-01';
      }
    }


    if(this.selected){
      if(this.type=="Y-m"){
        var selected=this.selected+"-01";
      }else if(this.type=="Y-m-d"){
        var selected=this.selected;
      }

      const setDate = new Date(putil.getDate(selected));
      const end = (new Date((settings.endTime && putil.getDate(settings.endTime)) || ''+(date.getFullYear()+10)+'-01-01').getTime());
      const start = (new Date((settings.startTime &&  putil.getDate(settings.startTime)) || '1950-01-01').getTime());
      //验证输入的年的范围是否正确
      if(setDate.getTime()>= start && setDate.getTime()<=end){
        this.year = setDate.getFullYear();
        this.month =  setDate.getMonth() + 1;
        this.day =  setDate.getDate();
      }
    }

    let months = [1,12];
    let days = [1,31];
    let yearsList =[],monthsList = [],daysList = [];

    for(;years[0]<=years[1];years[0]++){
      yearsList.push(years[0]+'年')
    }
    for(;months[0]<=months[1];months[0]++){
      var ileng=months[0].toString().length;
      if(ileng=="1"){
        months[0]=new Array(2).join("0")+months[0];
      }
      monthsList.push(months[0]+'月')
    }
    for(;days[0]<=days[1];days[0]++){
      var ileng=days[0].toString().length;
      if(ileng=="1"){
        days[0]=new Array(2).join("0")+days[0];
      }
      daysList.push(days[0]+'日')
    }

    settings.dataList = [
      yearsList,monthsList,daysList
    ]

    this.dataList=settings.dataList;
    this.startTime=settings.startTime; //开始时间
    this.endTime=settings.endTime;  //截至时间

    this.tempSelectedyear=this.year; //临时值
    this.tempSelectedmonth=this.month; //临时值
    this.tempSelectedday=this.day; //临时值

    /*this.year=settings.year;
    this.month=settings.month;
    this.day=settings.day;*/

    //console.log(JSON.stringify(this.dataList,null,"\t"))

  },
 mounted(){
     this.setMonth()
 },
  methods:{
    sel(){
      const date = putil.getDate(this.year+'-'+this.month+'-'+this.day);
      const arr = date.toString().split('-');

      this.tempSelectedyear=arr[0]; //临时值
      this.tempSelectedmonth=arr[1]; //临时值
      this.tempSelectedday=arr[2]; //临时值
      if(this.type=="Y-m"){
        this.$emit('onConfirmDate', arr[0]+"-"+arr[1]);
      }else if(this.type=="Y-m-d"){
        this.$emit('onConfirmDate', arr[0]+"-"+arr[1]+"-"+arr[2]);
      }


    },
    setMonth(){
      let c2 = this.month == 2;
      let c1 = [1,3,5,7,8,10,12].join().indexOf(parseInt(this.month));
      let m = '',newM  = []; // 日
      if(c2){
        if(this.isR){
          m = [1,29];
        }else{
          m= [1,28];
        }
      }else if(c1<0){
        m = [1,30];
      }else{
        m = [1,31];
      }
      let mArr = [],m2 = [1,12]; //月
      if(this.endTimeArr){

        if(this.year == + this.endTimeArr[0]){
          m2[1] = + this.endTimeArr[1]

          if(this.month== +this.endTimeArr[1]){
            m[1] = + this.endTimeArr[2]
          }

        }
      }
      if(this.startTimeArr){

        if(this.year == + this.startTimeArr[0]){
          m2[0] = + this.startTimeArr[1]

          if(this.month == +this.startTimeArr[1]){
            m[0] = + this.startTimeArr[2]
          }

        }
      }

      for(let i= m[0];i<=m[1];i++){
        var ileng=i.toString().length;
        if(ileng=="1"){
          i=new Array(2).join("0")+i;
        }
        newM.push(i+'日')
      }
      for(let i= m2[0];i<= m2[1];i++){
        var ileng=i.toString().length;
        if(ileng=="1"){
          i=new Array(2).join("0")+i;
        }
        mArr.push(i+'月')
      }

      this.dataList[2] = newM;
      this.dataList[1] = mArr;
    },
    // 确定数值的回调
    change(val,key,type = ''){

      if(type=='day'){
        this.day = val.match(/\d*/g)[0];
      }else if(type=='year'){
        this.year = val.match(/\d*/g)[0];
        this.setMonth()
      }else if(type=='month'){
        this.month = val.match(/\d*/g)[0];
        this.setMonth()
      }
    },
    /**
     * 关闭后 复位已选中的值
     */
    locateWheelByVal(){
      if(this.type=="Y-m"){
        this.$refs.itemYear.moveTo(this.tempSelectedyear);
        this.$refs.itemMonth.moveTo(this.tempSelectedmonth);
      }else if(this.type=="Y-m-d"){
        this.$refs.itemYear.moveTo(this.tempSelectedyear);
        this.$refs.itemMonth.moveTo(this.tempSelectedmonth);
        this.$refs.itemDay.moveTo(this.tempSelectedday);
      }
    },
    dateType(type){
        this.locateWheelByVal();
        document.getElementById('winbody').style.overflow = "visible"
        this.popShow=false;
        this.$emit('onDateType', type);
    },
    /**
     * 取消
     */
    qxCancel(){
      this.locateWheelByVal();

      document.getElementById('winbody').style.overflow = "visible"
    },
    /**
     * 确定
     */
    qrCancel(val){
        document.getElementById('winbody').style.overflow = "visible"
        this.sel();
    }
  }

}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->

<style lang="scss" scoped>
  .m-picker-item-box{
    display: flex;
    justify-content: center;
    align-items: center;
    align-content: center;
    overflow: hidden;
    background: #fff;
    width: 100%;
  }
  .dateType{
    border-bottom: 1px solid #FFFFFF;
    background: transparent;
    margin-top: px2rem(15px);
    margin-bottom: px2rem(15px);
    padding-left: px2rem(30px);
    padding-right:px2rem(30px);
    box-sizing: border-box;
    display: -webkit-box;
    display: -webkit-flex;
    display: flex;
    -webkit-box-pack: justify;
    -webkit-justify-content: space-between;
    justify-content: space-between;
    &:after{
     background-color: transparent;
    }
    .button{
      width: 25%;
      padding:0rem  px2rem(15px);
      span{
        border:1px solid #2aa2aa;
        color: #2aa2aa;
        display: inline-block;
        border-radius:5px;
        width: 100%;
        height: px2rem(80px);
        line-height: px2rem(80px);
      }
      &.active{
         border-color:#FFFFFF;
          span{
            color: #2aa2aa;
          }
       }
    }
  }
  .dateTimeMonth{
    background: #EBEBEB;
    height: px2rem(95px);
    line-height: px2rem(95px);
    text-align: center;
    color: #666666;
  }
</style>
